package com.juzhencms.apps.busi.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Arrays;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.IpAddressUtil;
import com.juzhencms.apps.base.common.util.JWTUtil;
import com.juzhencms.apps.base.common.util.MD5Util;
import com.juzhencms.apps.base.common.util.WebUtil;

import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;


@Controller
@Slf4j
@RequestMapping("/login")
public class LoginController  extends BaseController{
	
	@Autowired
    private JWTUtil jwtUtil;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/doLogin",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String doLogin(HttpServletRequest request,HttpServletResponse response){
		
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String validateNUM=request.getParameter("validateNUM");
		String validateToken=request.getParameter("validateToken");
		
		if(username==null || username.equals("") || password==null || password.equals("") || validateNUM==null || validateNUM.equals("") || validateToken==null){
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "参数有误");
			return WebUtil.resultString(result,request);
		}
		
		if(!jwtUtil.validateImgCode(validateToken, validateNUM)){
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "验证码错误");
			return WebUtil.resultString(result,request);
		}
			
		/*HttpSession session=request.getSession();
		String validateCode="";
		if(session.getAttribute("validateNUM")!=null){
			validateCode= session.getAttribute("validateNUM").toString();
			session.removeAttribute("validateNUM");
		}
		
		
		if(validateCode==null || validateCode.equals("") || !validateCode.equals(validateNUM)){
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "验证码有误");
			return WebUtil.resultString(result,request);
		}*/
		
		//根据用户更名查询用户信息
		Map userRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where (user=? or mobile=?) and publish=1 and del_flag=0 limit 0,1",new Object[]{username,username});
		if(userRecord==null || userRecord.get("pass")==null){
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "用户不存在或未开通");
			return WebUtil.resultString(result,request);
		}
		
		Date last_login_fail_time=(Date)userRecord.get("last_login_fail_time");//上次登录失败时间
		int login_fail_times=new Integer(userRecord.get("login_fail_times").toString()).intValue();//之前登录失败的次数
		if(last_login_fail_time!=null){
			Calendar cal = Calendar.getInstance();
			cal.setTime(last_login_fail_time); 
			cal.add(cal.DATE, 1); //加一天
			cal.getTime();
			if(cal.getTime().after(new Date()) && login_fail_times>=3){
				Map result=new HashMap();
				result.put("result",0);
				result.put("msg", "登录失败次数过多，请明天再试");
				return WebUtil.resultString(result,request);
			}
		}
		
		String passStr=MD5Util.md5(password+userRecord.get("pass_randstr"));
		
		if(userRecord.get("pass").toString().equals(passStr)){
			
			
			//清除失败限制
			if(login_fail_times>0){
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set login_fail_times=0 where id=?", new Object[]{userRecord.get("id")});
			}
			
			
			//生成jwt签名
			String userToken=userService.createUserToken(userRecord);
			
			//获取客户端信息
			UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
			
			//记录登录日志
			Map loginRecord=new HashMap();
			loginRecord.put("user_id", userRecord.get("id"));
			loginRecord.put("user", userRecord.get("user"));
			loginRecord.put("name", userRecord.get("name"));
			loginRecord.put("token", userToken);
			loginRecord.put("ip", IpAddressUtil.getIpAddress(request));
			loginRecord.put("client_system",userAgent.getOperatingSystem().toString());
			loginRecord.put("client_browser",userAgent.getBrowser().toString());
			loginRecord.put("create_time", new Date());
			this.getCommonService().getJdbcDao().addObj(DBTable.loginLog, loginRecord);
			
			//设置自动登录
			String remember_pwd=request.getParameter("remember_pwd");
			//将用户信息存储到cookie
			this.getUserService().setLoginCookie(userToken, remember_pwd, request, response);
			
			
			
			Map result=new HashMap();
			result.put("result",1);
			result.put("msg", "登录成功");
			
			return WebUtil.resultString(result,request);
		}else{
			//记录登录失败
			Map updateData=new HashMap();
			updateData.put("id", userRecord.get("id"));
			updateData.put("last_login_fail_time", new Date());
			
			if(last_login_fail_time!=null){
				Calendar cal = Calendar.getInstance();
				cal.setTime(last_login_fail_time); 
				cal.add(cal.DATE, 1); //加一天
				cal.getTime();
				if(cal.getTime().after(new Date())){
					updateData.put("login_fail_times", login_fail_times+1);
				}else{
					updateData.put("login_fail_times", 1);
				}
			}else{
				updateData.put("login_fail_times", 1);
			}
			
			this.getCommonService().getJdbcDao().updateObj(DBTable.user, updateData, "id");
			
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "用户名或密码有误");
			
			return WebUtil.resultString(result,request);
		}
	}
	
	@RequestMapping(value="/logout",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String logout(HttpServletRequest request,HttpServletResponse response){
		
		
		
		//清除自动登录
		this.getUserService().logout(request, response);
		

		Map result=new HashMap();
		result.put("result",1);
		return WebUtil.resultString(result,request);
	}
	
}
